package com.infinitus.activity.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.infinitus.activity.pojo.DO.AuldrawAddressDo;
import com.infinitus.activity.pojo.DO.AuldrawVo;
import com.infinitus.activity.pojo.VO.ActivityConfigVO;
import com.infinitus.activity.pojo.VO.QualificationVo;
import com.infinitus.activity.pojo.VO.ResponseVO;
import com.infinitus.activity.service.AuldrawService;
import com.infinitus.activity.service.impl.LotteryService;
import com.infinitus.activity.util.KeyGenerator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: luzhenjie
 * @create: 2019/3/11
 * @desc:
 */
@Controller
@RequestMapping(value = "/auldraw")
public class AuldrawController {

    private static Logger logger = Logger.getLogger(AuldrawController.class);

    @Autowired
    private AuldrawService auldrawService;


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ActivityConfigVO activityConfig;

    @Value("${deploycolId}")
    private String deploycolId;

    @Autowired
    private LotteryService lotteryService;


    /**
     * @Desc 根据卡号获取中奖纪录
     */
    @RequestMapping(value = "/winner/record", method = RequestMethod.GET)
    public ResponseEntity<?> selectAuldrawWinnerListByCardNo(String dealerNo) {
        Map<String, AuldrawVo> map = new HashMap<>();
        try {
            Map<Object, Object> stringMap = stringRedisTemplate.opsForHash().entries(KeyGenerator.getActivityListWinningBackup(deploycolId, dealerNo));
            for (Map.Entry<Object, Object> entry : stringMap.entrySet()) {
                AuldrawVo auldrawVo = JSONObject.parseObject(String.valueOf(entry.getValue()), AuldrawVo.class);
                if (!auldrawVo.getAwardsName().equals("8080") && !auldrawVo.getGiftCode().equals("8080")) {
                    map.put(String.valueOf(entry.getKey()), auldrawVo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(new ResponseVO<>().setContent(map));
    }

    /**
     * @Desc 填写收货地址
     */
    @RequestMapping(value = "/address/create", method = RequestMethod.POST)
    public ResponseEntity<?> createAuldrawAddress(@RequestBody AuldrawVo auldrawVo) {
        try {
            //将收货地址保存到redis中
            String dealerNo = auldrawVo.getDealerNo();       //卡号
            String qualiSeqNo = auldrawVo.getQualiSeqNo();   //资格序列号
            //获取卡号对应的中奖纪录
            Object jsonString = stringRedisTemplate.opsForHash().get(KeyGenerator.getActivityListWinningBackup(deploycolId, dealerNo), qualiSeqNo);
            AuldrawVo auldrawVo1 = JSONObject.parseObject(String.valueOf(jsonString), AuldrawVo.class);
            //保存收货信息
            auldrawVo1.setReceiverName(auldrawVo.getReceiverName());
            auldrawVo1.setReceiverPhone(auldrawVo.getReceiverPhone());
            auldrawVo1.setProvinceCode(auldrawVo.getProvinceCode());
            auldrawVo1.setCityCode(auldrawVo.getCityCode());
            auldrawVo1.setTownCode(auldrawVo.getTownCode());
            auldrawVo1.setDetailAddress(auldrawVo.getDetailAddress());
            //设置回Redis
            stringRedisTemplate.opsForHash().put(KeyGenerator.getActivityListWinningBackup(deploycolId, dealerNo), qualiSeqNo, JSON.toJSONString(auldrawVo1));
            //用于同步
            stringRedisTemplate.opsForHash().put(KeyGenerator.getActivityListWinningSynch(deploycolId, dealerNo), qualiSeqNo, JSON.toJSONString(auldrawVo1));//有地址
            return ResponseEntity.ok(new ResponseVO<>().setContent("保存地址成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(new ResponseVO<>().setContent("保存地址失败"));
        }
    }


    /**
     * @Desc 根据卡号获取资格可抽奖次数
     */
    @RequestMapping(value = "/quali/count", method = RequestMethod.GET)
    public ResponseEntity<?> qualiCount(String dealerNo) {
        Map<String, String> map = new HashMap<>();
        //map.put("isSyc",activityConfig.activityConfigVO().getRuleType());
        Integer count = 0;
        //有資格抽獎
        //logger.info(activityConfig.hashCode() + "------ruletype" + activityConfig.getRuleType());
        if (activityConfig.getRuleType().equals("1")) {
            Map<Object, Object> stringMap = stringRedisTemplate.opsForHash().entries(deploycolId + ":" + dealerNo);
            for (Map.Entry<Object, Object> entry : stringMap.entrySet()) {
                QualificationVo qualificationVo = JSONObject.parseObject(String.valueOf(entry.getValue()), QualificationVo.class);
                if (qualificationVo.getQualiStatus() == 1) {
                    count++;
                }
            }
        } else if (activityConfig.getRuleType().equals("0") || activityConfig.getRuleType().equals("2")) {
            if (lotteryService.checkCanLottery(dealerNo, activityConfig.getRuleType())) {
                count++;
            }
        }
        map.put("count", count + "");
        return ResponseEntity.ok(new ResponseVO<>().setContent(map));
    }


    /**
     * 根据卡号获取已填写的收货地址
     *
     * @param cardNo
     * @return
     */
    @RequestMapping(value = "/address/{cardNo}", method = RequestMethod.GET)
    public ResponseEntity<?> selectAuldrawAddressListByCardNo(@PathVariable("cardNo") String cardNo) {
        List<AuldrawAddressDo> auldrawAddressDoList = auldrawService.selectAuldrawAddressListByCardNo(cardNo);
        return ResponseEntity.ok(new ResponseVO<>().setContent(auldrawAddressDoList));
    }
}